package com.imachen.org.service.impl;

import com.imachen.basic.service.impl.BaseServiceImpl;
import com.imachen.org.domain.Department;
import com.imachen.org.mapper.DepartmentMapper;
import com.imachen.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        //将所有的部门添加的Map中 - 为了根据id去获取
        List<Department> departments = departmentMapper.findAll();
        Map<Long,Department> map =  new HashMap<>();
        //将每一个部门的id和对象保存在Map
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        //查询部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            //如果没有父id - 顶级部门
            if(department.getParent_id()==null){//顶级部门
                deptTree.add(department);
            }else{
                //获取父部门id
                Long parent_id = department.getParent_id();
                //获取父部门
                Department parentDept = map.get(parent_id);
                //将自己添加到父部门的Children中
                parentDept.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
